using System;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using System.Collections.Generic;

namespace Utils
{
public class NetUtil
{
	static object SpinLock = new object();

	public static void log(string msg)
	{
		lock(SpinLock)
		{
			string path = System.Web.HttpContext.Current.Server.MapPath("./logs/");
			if(!Directory.Exists(path))
			{
				Directory.CreateDirectory(path);
			}
			StreamWriter sw = File.AppendText(path + DateTime.Now.ToString("yyyyMMdd") + ".log");
			sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")+","+msg);
			sw.Close();
		}
	}

	public static string post(string url, string postData, string acccess_token)
	{
		const string contentType = "application/x-www-form-urlencoded";
		System.Net.ServicePointManager.Expect100Continue = false;

		CookieContainer cookies = new CookieContainer();
		HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
		webRequest.Method = "POST";
		webRequest.ContentType = contentType;
		webRequest.CookieContainer = cookies;
		webRequest.ContentLength = postData.Length;
		
		if(!string.IsNullOrEmpty(acccess_token))
			webRequest.Headers["Authorization"] = "Bearer " + acccess_token;
		else if(!string.IsNullOrEmpty(Global.CLIENT_SECRET))
		{
			string authInfo = Global.CLIENT_ID + ":" + Global.CLIENT_SECRET;
			authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
			webRequest.Headers["Authorization"] = "Basic " + authInfo;
		}

		StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
		requestWriter.Write(postData);
		requestWriter.Close();

		string responseData = "";

		try
		{
			using (WebResponse response = webRequest.GetResponse())
			{
				StreamReader responseReader = new StreamReader(response.GetResponseStream());
				responseData = responseReader.ReadToEnd();
				responseReader.Close();
				
				log("response on posting to ["+url+"], responseData=" + responseData);
			}
		}
		catch (WebException e)
		{
			string msg = "";
			using (WebResponse response = e.Response)
			{
				HttpWebResponse httpResponse = (HttpWebResponse) response;
				msg = string.Format("Error code: {0}; ", httpResponse.StatusCode);
				using (Stream data = response.GetResponseStream())
				{
					using (StreamReader reader = new StreamReader(data))
					{
						msg += reader.ReadToEnd();
					}
				}
			}
			log("ERROR on post, msg=" + msg);
			throw new Exception(msg);
		}

		return responseData;
	}

	public static string get(string url, string acccess_token)
	{
		CookieContainer cookies = new CookieContainer();
		HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
		webRequest.Headers["Authorization"] = "Bearer " + acccess_token;
		webRequest.CookieContainer = cookies;

		string responseData = "";

		try
		{
			using (WebResponse response = webRequest.GetResponse())
			{
				StreamReader responseReader = new StreamReader(response.GetResponseStream());
				responseData = responseReader.ReadToEnd();
				responseReader.Close();
				
				log("got from ["+url+"], responseData=" + responseData);
			}
		}
		catch (WebException e)
		{
			string msg = "";
			using (WebResponse response = e.Response)
			{
				HttpWebResponse httpResponse = (HttpWebResponse) response;
				msg = string.Format("Error code: {0}, {1}; ", (int)httpResponse.StatusCode, httpResponse.StatusCode);
				using (Stream data = response.GetResponseStream())
				{
					using (StreamReader reader = new StreamReader(data))
					{
						msg += reader.ReadToEnd();
					}
				}
			}
			log("ERROR on get, msg=" + msg);
			throw new Exception(msg);
		}

		return responseData;
	}
}
}